package com.maychat.websocket.netty;

import com.maychat.config.Consts;
import com.maychat.pojo.UserInfoToken;
import com.maychat.service.impl.RedisServiceImpl;
import com.maychat.websocket.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    RedisServiceImpl redisService;

    @Autowired
    ChannelContextUtils channelContextUtils;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("有新的连接加入");
    }

    // 仅用于接收心跳
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame txt) {
        Channel channel = ctx.channel();
        Attribute<String> attr = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attr.get();
        log.info("收到userId为{}的消息 {}", userId, txt.text());
        redisService.saveUserConnHeartBeat(userId);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("有连接断开");
        channelContextUtils.removeContext(ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete e) {
            HttpHeaders headers = e.requestHeaders();
            String tokenStr = headers.get(Consts.AUTH);
            if (StringUtils.isBlank(tokenStr)) {
                ctx.channel().close();
                return;
            }
            UserInfoToken tokenObj = redisService.getUserToken(tokenStr);
            if (tokenObj == null) {
                ctx.channel().close();
                return;
            }
            channelContextUtils.addContext(tokenObj.getUserId(), ctx.channel());
        }
    }
}
